package twopointer;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

/**
 * 167. 两数之和 II - 输入有序数组
 * https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
 */
public class TwoSum {

    public static void main(String[] args) {
        int[] nums = {2,7,6,11,15};
//        int[] nums = {3,2,4};
        int target = 9;
        int[] result = new TwoSum().twoSum2(nums, target);
        System.out.println(JSON.toJSONString(result));
    }

    public int[] twoSum0(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }
        int len = nums.length;
        int start = 0;
        int end = len - 1;
        while (start < end) {
            int sum = nums[start] + nums[end];
            if (sum == target) {
                return new int[]{start, end};
            } else if (sum > target) {
                end--;
            } else {
                start++;
            }
        }
        return new int[0];
    }


    public int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }
        int len = nums.length;
        int start = 0;
        int end = len - 1;
        while (start < end) {
            if (nums[start] + nums[end] < target) {
                start++;
            } else if (nums[start] + nums[end] > target) {
                end--;
            } else {
                return new int[]{start, end};
            }
        }
        return new int[0];
    }


    /**
     * 暴力解法双重循环
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum2(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            for (int j = i+1; j < len; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    /**
     * Hash
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum3(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }
        int len = nums.length;
        // key是y元素，val是元素索引i；利用hash存储 target - x 的 y值
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < len; i++) {
            int x = nums[i];
            if (cache.containsKey(target - x)) {
                return new int[]{cache.get(target - x), i};
            }
            cache.put(x, i);
        }
        return new int[0];
    }
}
